import os
import joblib
import pandas as pd
from joblib import Parallel, delayed

os.getcwd()

def sdf_single_scorecard_ply(dx, cardx, x):
    card_dict = dict(cardx[["bin", "points"]].to_dict("split")["data"])
    card_dict_interval = {
        i: j for i, j in card_dict.items() if type(i) == pd._libs.interval.Interval
    }
    card_dict_special = {
        i: j for i, j in card_dict.items() if type(i) != pd._libs.interval.Interval
    }
    special_values = list(card_dict_special)
    dx_special = dx[dx.isin(special_values)]
    dx_inter = dx[~dx.isin(special_values)]
    score = pd.concat(
        [dx_special.map(card_dict_special), dx_inter.map(card_dict_interval)], axis=0
    )
    return score

def sdf_scorecard_ply(data, card, only_total_score=True, var_kp=None):
    cardx = pd.concat(card, ignore_index=True)
    dt = data.copy(deep=True)
    cols = list(cardx.variable.unique())
    cols.remove("basepoints")
    dt[cols] = dt[cols].fillna("nan")
    parallel_score = Parallel(n_jobs=-1)(
        delayed(sdf_single_scorecard_ply)(dt[v], cardx[cardx.variable == v], v)
        for v in cols
    )
    try:
        data_score = pd.concat(parallel_score + [data[var_kp]], axis=1)
    except:
        data_score = pd.concat(parallel_score, axis=1)
    data_score["score"] = (
        data_score.sum(axis=1)
        + cardx[cardx.variable == "basepoints"]["points"].values[0]
    )
    if only_total_score:
        data_score.drop(columns=cols, inplace=True)
    return data_score


os.chdir('D:\\项目\\6.18_建模_阳光消金')
card = joblib.load('card.pkl')

os.chdir(r'D:\项目\8.9_模型上线_阳光消金小米（V2）\0.模型打分_3000条测试样本')
df = pd.read_csv('test_3000_postman_001.csv',low_memory = False,index_col = 'cus_num',skiprows = [1]) # 3000测试样本打分
df

df = df.fillna(-99) # 缺失值填充

score = sdf_scorecard_ply(df, card)
score[score <= 300] = 300
score[score >= 1000] = 1000

score.to_csv('3000样本模型打分.csv')



